<template>
  <el-dialog class="dialog_file" :visible.sync="dialog_files" width="10rem" @open="openDialog" @close="closeDialog" :close-on-click-modal="false">
    <div slot="title" class="title">上传{{ title }}</div>
    <el-form ref="ruleForm_file" :model="ruleForm_file" :rules="rules" label-width="1.2rem">
      <el-form-item prop="approveProcess" label="审批流程：">
        <el-select v-model="ruleForm_file.approveProcess" placeholder="请选择">
          <el-option v-for="(item, index) in options" :key="index" :label="item" :value="item" style="font-size: 0.16rem;" />
        </el-select>
      </el-form-item>
      <el-form-item :label="`上传${title}：`">
        <el-upload
          ref="uploads"
          class="upload-demo"
          :multiple="false"
          :action="action"
          :on-remove="handleRemove"
          :on-change="handleChange"
          :limit="1"
          :file-list="ruleForm_file.fileList"
          :auto-upload="false"
        >
          <el-button :loading="loading" slot="trigger" size="small" type="primary" :disabled="ruleForm_file.fileList.length>0">{{loading?'上传中':'选取文件'}}</el-button>
        </el-upload>
      </el-form-item>
      <!-- <div class="el-upload__tip">注：{{ Tips }}</div> -->
      <el-form-item v-if="tabs == 'video'" label="视频标题：" prop="title" class="terminalType">
        <el-input v-model="ruleForm_file.title" placeholder="请输入内容" clearable />
      </el-form-item>
      <el-form-item v-if="tabs == 'video'" label="视频描述：" prop="introduction" class="terminalType">
        <el-input v-model="ruleForm_file.introduction" placeholder="请输入内容" clearable />
      </el-form-item>
      <el-form-item label="终端类别：" prop="terminalType" class="terminalType">
        <el-checkbox-group v-model="ruleForm_file.terminalType" @change="checkboxGroup">
          <el-checkbox v-for="item in checkOptions" :key="item.code" :label="item.code" :disabled="item.code=='wxList'&&tabs=='file'">{{ item.name }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <div v-for="(item, index) in checkTable" :key="index" class="terminal" v-show="ruleForm_file.terminalType.includes(item.key)">
      <p><svg-icon icon-class="right" style="color:#516FE9;" /> {{ item.label }}</p>
      <el-table :ref="`${item.key}file`" :data="item.data" border style="width: 100%" @select="selection(item.key)" @selection-change="selectionChange" @select-all="selection(item.key)">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" width="80" label="序号" align="center" />
        <el-table-column v-for="(data, key) in item.header" :key="key" :prop="data.key" :label="data.label" align="center" />
      </el-table>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" :disabled="ruleForm_file.fileList.length>0?false:true" @click="Submission('ruleForm_file', 'hold')">保 存</el-button>
      <el-button type="primary" :disabled="ruleForm_file.fileList.length>0?false:true" @click="Submission('ruleForm_file', 'submit')">提 交</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { bus } from '@/main'

export default {
  data() {
    const validCheck = (rule, value, callback) => {
      if (!this.ruleForm_file.terminalType.length > 0) {
        callback(new Error('请选择终端类别'))
      } else {
        callback()
      }
    }
    return {
      options: [],           // 审批流程
      ruleForm_file: {
        approveProcess: '',  // 审批流程
        fileList: [],        // 文件上传
        fileId: '',          // 上传文件返回的文件id
        wxList: '',          // 微信
        ydList: '',          // 移动服务平台
        otherList: '',       // 其他软件平台
        hardwareList: '',    // 硬件终端
        terminalType: [],    // 选中的终端
        title: '',           // 视频标题
        introduction: ''     // 视频描述
      },
      tableIndex: '',        // 当前图文下标
      checkOptions: [],      // 终端类别Options
      terminalList: {        // 终端列表
        wxList: [],          // 微信
        ydList: [],          // 移动服务平台
        otherList: [],       // 其他软件平台
        hardwareList: []     // 硬件终端
      },
      checkTable: [],        // 终端table
      rules: {
        approveProcess: [
          { required: false, trigger: 'change' }
        ],
        fileList: [
          { required: true, trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入视频标题', trigger: 'blur' }
        ],
        introduction: [
          { required: true, message: '请输入视频描述', trigger: 'blur' }
        ],
        terminalType: [
          { required: true, validator: validCheck, trigger: 'blur' }
        ]
      },
      Tips: '',            // 注意事项
      title: '',           // 标题（上传视频素材时的素材标题）
      tabs: '',            // 父级tab类型
      reg: '',             // 文件格式
      fileSize: 0,         // 文件大小，单位：M
      loading: false,
      dialog_files: false  // 弹窗开关
    }
  },
  computed: {
    action() {
      const api = `${process.env.VUE_APP_BASE_API}/common/uploadFile`
      return api
    }
  },
  methods: {
    // 获取父级参数
    getParam(param) {
      this.tabs = param.tabs
      this.dialog_files = param.open
    },
    // 打开上传弹窗
    openDialog() {
      const _this = this
      // 审批流程下拉框
      this.$api.getApproveProcess().then(response => {
        if (response.data.status == 1) {
          _this.options = response.data.data
          _this.ruleForm_file.approveProcess = _this.options[0]
        } else {
          this.$message.error(response.data.msg)
        }
      })
      // 请求终端类型
      this.$api.getTerminal().then((response) => {
        if (response.data.status == 1) {
          _this.checkOptions = response.data.data
        } else {
          this.$message.error(response.data.msg)
        }
      })
      // 请求终端列表
      this.$api.getTerminalList().then((response) => {
        if (response.data.status == 1) {
          _this.terminalList = response.data.data
          this.checkTableFN()
        } else {
          this.$message.error(response.data.msg)
        }
      })
      // 根据父级传入的tab值，切换判断上传文件格式的正则与文件大小
      switch (this.tabs) {
        case 'image': // 图片
          this.Tips = '只能上传格式为 jpg、jpeg、bmp、png 的文件，且不超过大小不超过5M！'
          this.title = '图片'
          this.reg = /(.*)\.(jpg|bmp|jpeg|png)$/
          this.fileSize = 5 // 5M
          break
        case 'file': // 文件
          this.Tips = '只能上传格式为 doc、docx、xls、xlsx、ppt、pptx、pdf、rar、zip 的文件，且不超过大小不超过100M！'
          this.title = '文件'
          this.reg = /(.*)\.(doc|docx|xls|xlsx|ppt|pptx|pdf|rar|zip)$/
          this.fileSize = 100 // 100M
          break
        case 'voice': // 语音
          this.Tips = '只能上传格式为 doc、docx、xls、xlsx、ppt、pptx、pdf、rar、zip 的文件，且不超过大小不超过100M！'
          this.title = '语音'
          this.reg = /(.*)\.(mp3)$/
          this.fileSize = 100 //
          break
        case 'video': // 视频
          this.Tips = '只能上传格式为 doc、docx、xls、xlsx、ppt、pptx、pdf、rar、zip 的文件，且不超过大小不超过100M！'
          this.title = '视频'
          this.reg = /(.*)\.(mp4)$/
          this.fileSize = 100 //
          break
        default:
          break
      }
    },
    // 关闭上传弹窗
    closeDialog() {
      this.ruleForm_file = {
        approveProcess: this.options[0],
        fileList: [],
        wxList: '', // 微信
        ydList: '', // 移动服务平台
        otherList: '', // 其他软件平台
        hardwareList: '', // 硬件终端
        terminalType: []
      }
      this.terminalList = {
        wxList: [],
        ydList: [],
        otherList: [],
        hardwareList: []
      },
      this.checkTable = []
      this.reg = ''
      this.fileSize = 0
      this.dialog_file = false
    },
    // 移除文件
    handleRemove(file, fileList) {
      const arr = this.ruleForm_file.fileList
      const newArr = []
      for (const i in arr) {
        if (arr[i].uid != file.uid) {
          newArr.push(arr[i])
        }
      }
      this.ruleForm_file.fileList = newArr
    },
    // 上传文件检验
    handleChange(file, fileList) {
      // 文件类型、大小判断
      if ((file.size / 1024 / 1024) <= this.fileSize && this.reg.test(file.name)) {
        const name = file.name
        const arr = this.ruleForm_file.fileList
        // 如列表中已上传文件，再次上传时，校验文件是否重复
        if (arr.length > 1) {
          for (const i in arr) {
            if (name == arr[i].name) {
              fileList.splice(-1, 1) // 如上传文件已存在，删除
              this.ruleForm_file.fileList = fileList
              return this.$message.error('请勿上传同一文件！')
            } else {
              this.ruleForm_file.fileList = fileList
              this.customUpload({file: file.raw})
            }
          }
        } else {
          this.ruleForm_file.fileList = fileList
          this.customUpload({file: file.raw})
        }
      } else {
        fileList.splice(-1, 1) // 删除不符合要求的文件
        this.ruleForm_file.fileList = fileList
        return this.$message.error('暂不支持上传该类型文件，请重新选择！')
      }
    },
    // 上传
    customUpload(file) {
      const data = new FormData()
      data.append('files', file.file)
      data.append('type', this.tabs)
      this.loading = true
      this.$api.upload(data).then((response) => {
        if (response.data.status == 1) {
          this.loading = false
          this.ruleForm_file.fileId = response.data.data
          this.$message.success('文件上传成功！')
        } else {
          this.loading = false
          this.ruleForm_file.fileList = []
          this.ruleForm_file.fileId = ''
          this.$message.error('文件上传失败，请重试！')
        }
      }).catch(() => {
        this.loading = false
        this.ruleForm_file.fileList = []
        this.ruleForm_file.fileId = ''
        this.$message.error('文件上传失败，请重试！')
      })
    },
    // 发布终端table
    checkTableFN() {
      this.checkTable = [
        {
          label: '微信公众号',
          key: 'wxList',
          header: [
            { label: '微信公众号名称', key: 'name' },
            { label: '负责人', key: 'manager' }
          ],
          data: this.terminalList.wxList
        },
        {
          label: '移动服务平台',
          key: 'ydList',
          header: [
            { label: '移动服务平台名称', key: 'name' },
            { label: '负责人', key: 'manager' }
          ],
          data: this.terminalList.ydList
        },
        {
          label: '其他软件终端',
          key: 'otherList',
          header: [
            { label: '软件终端名称', key: 'name' },
            { label: '栏目', key: 'section' },
            { label: '负责人', key: 'manager' }
          ],
          data: this.terminalList.otherList
        },
        {
          label: '硬件终端',
          key: 'hardwareList',
          header: [
            { label: '硬件终端名称', key: 'name' },
            { label: '负责人', key: 'manager' }
          ],
          data: this.terminalList.hardwareList
        }
      ]
    },
    // 终端类别
    checkboxGroup() {
      const keyArr = Object.keys(this.terminalList)
      keyArr.forEach(item => {
        if (!this.ruleForm_file.terminalType.includes(item)) {
          this.ruleForm_file[item] = ''
          this.$refs[`${item}file`][0].clearSelection();
        }
      });
    },
    selection(key) {
      this.tableIndex = key
    },
    selectionChange(data) {
      setTimeout(() => {
        const arr = []
        for (const i in data) {
          arr.push(data[i].id)
        }
        this.ruleForm_file[this.tableIndex] = arr.join(',')
      }, 500)
    },
    // 上传图片/文件 - 提交
    Submission(formName, key) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const checkList = this.ruleForm_file.terminalType
          let num = false
          for (let i = 0; i < checkList.length; i++) {
            const key = checkList[i]
            if (!this.ruleForm_file[key].length > 0) {
              num = false
              return this.$message.error('请选择需发布的终端')
            } else {
              num = true
            }
          }
          if (num) {
            const obj = JSON.parse(JSON.stringify(this.ruleForm_file))
            if (obj.terminalType.length == 1) {
              obj.terminalType = obj.terminalType[0]
            } else {
              for (const i in obj.terminalType) {
                const key = obj.terminalType[i]
              }
              obj.terminalType = obj.terminalType.join(',')
            }
            if (key == 'hold') {
              this.$api[`hold${this.tabs}`](obj).then((response) => {
                if (response.data.status == 1) {
                  this.dialog_files = false
                  bus.$emit('refreshList')
                  this.$message.success(response.data.msg)
                } else {
                  this.$message.error(response.data.msg)
                }
              })
            } else if (key == 'submit') {
              this.$api[`submitAdd${this.tabs}`](obj).then((response) => {
                if (response.data.status == 1) {
                  this.dialog_files = false
                  bus.$emit('refreshList')
                  this.$message.success(response.data.msg)
                } else {
                  this.$message.error(response.data.msg)
                }
              })
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog_file {
  >>>.el-dialog{
    overflow: hidden;
    border-radius: 0.05rem;
    * {
      font-size: 0.16rem;
    }
    .el-dialog__header {
      background: #536FEA;
      padding: 0 0.2rem;
      height: 0.55rem;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .title, .el-dialog__close {
        color: #fff;
        font-size: 0.2rem;
      }
      .el-dialog__headerbtn {
        position: static;
      }
    }
    .el-dialog__body {
      padding: 0.15rem 0.2rem;
      .el-upload__tip {
        color:red;
        width:78%;
        margin: 0 auto;
        line-height: 0.2rem;
      }
      .el-form {
        .el-form-item__label {
          font-size: 0.16rem;
        }
      }
    }
    .el-dialog__footer {
      padding: 0 0.2rem 0.2rem;
    }
  }
}
</style>
